package DataCollect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MakeWeather {
    public static String getWeather(String lng,String lat) throws IOException {
        //定义key
        String key = "870d1cd893ab43b998a376c460369e10";
        //拼接url字符串
        String urlStr = "https://free-api.heweather.com/s6/weather/now?&location="+lng+","+lat+"&key="+key;
        //调用requsetWea获取json天气数据
        String weatherJson = requsetWea(urlStr);
        //System.out.println(weatherJson);
        //调用解析json程序
        //return
        return parseJson(weatherJson);

    }

    private static String parseJson(String weatherJson) {
        String weather = "";
        if (StringUtils.isNotEmpty(weatherJson)){
            JSONObject jsonObject = JSON.parseObject(weatherJson);
            JSONArray heWeather6Array = jsonObject.getJSONArray("HeWeather6");
            if (heWeather6Array.size()==0){
                return null;
            }

            JSONObject jsonObject1 = heWeather6Array.getJSONObject(0);
            String status = jsonObject1.getString("status");
            if (status.equals("ok")){
                JSONObject now = jsonObject1.getJSONObject("now");
                //获取cond_txt wind_dir hum
                String cond_txt = now.getString("cond_txt");
                String wind_dir = now.getString("wind_dir");
                String hum = now.getString("hum");

                if (cond_txt.contains("雨")){
                    weather = "雨";
                } else if (cond_txt.contains("雪")){
                    weather = "雪";
                }else if (cond_txt.contains("冰雹")){
                    weather = "冰雹";
                }else if (cond_txt.contains("扬沙")){
                    weather = "扬沙";
                }else if (cond_txt.contains("浮尘")){
                    weather = "浮尘";
                }else {
                    if (wind_dir.contains("风")){
                        weather = "风";
                    }else {
                        weather = "晴";
                    }
                }

                weather = weather + "|" + hum;
            }else {
                weather = "晴|0";
            }


        }
        return weather;
    }

    private static String requsetWea(String urlStr) throws IOException {
        //获取url
        URL url = new URL(urlStr);
        //创建url连接
        URLConnection urlConnection = url.openConnection();
        //获取数据
        InputStream inputStream = urlConnection.getInputStream();
        //将数据转为字符串
        return IOUtils.toString(inputStream);
    }
}
